package persistence;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import model.AlarmLog;

/**
 * Save class
 * @author Adrien Ledeul
 * @version 0.1
 */
public class Save
{
	/**
	 * Serialize the log file
	 */
    public static void serialize(ArrayList<AlarmLog> log)
    {
        FileOutputStream file = null;
        ObjectOutputStream oos = null;

        try
        {
            file = new FileOutputStream("save.log");
            oos = new ObjectOutputStream(file);

            try
            {
                for (AlarmLog l : log)
                {
                    oos.writeObject(l);
                    oos.flush();
                }
            }
            catch (java.io.IOException e)
            {
                JOptionPane.showMessageDialog(null, "Internal Error : The log file cannot be updated", "Error", JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            }
            finally
            {
                oos.close();
            }
        }
        catch (java.io.IOException e)
        {
        }
    }
    
	/**
	 * Unserialize the log file
	 */
    public static ArrayList<AlarmLog> unserialize()
    {
    	ArrayList<AlarmLog> log = new ArrayList<AlarmLog>();

        try
        {
            FileInputStream file = new FileInputStream("save.log");
            ObjectInputStream ois = new ObjectInputStream(file);
            while (true)
            {
                Object o = ois.readObject();
                if (o != null)
                {
                    AlarmLog l = (AlarmLog) o;
                    log.add(l);
                }
            }
        }
        catch (java.io.IOException e)
        {
            System.out.println("End of unserialization");
        }
        catch (ClassNotFoundException e)
        {
        }
        return log;
    }
}
